package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 自媒体端登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1.参数校验
        //1.1获取用户名
        String name = dto.getName();
        //1.2获取密码
        String password = dto.getPassword();
        //1.3判断用户名和密码是否为空
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }
        //2.根据用户名进行查询
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //2.1判断用户名是否为空
        if (wmUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不能为空");
        }
        //3.对用户密码用md5加密处理
        String oldpwd = DigestUtils.md5DigestAsHex((password + wmUser.getSalt()).getBytes());
        //3.1判断是否与原密码相同
        if (!oldpwd.equals(wmUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"密码不一致");
        }
        //4.判断用户的状态是否为9
        if (wmUser.getStatus().intValue()!=9){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户状态无效");
        }
        //5.修改登录时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);
        //6.颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        //7.用户信息返回到vo实体类中
        WmUserVO userVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,userVO);
        //8.返回响应的结果
        Map map=new HashMap<>();
        map.put("token",token);
        map.put("user",userVO);
        return ResponseResult.okResult(map);
    }
}
